package com.earthchen.demo.controller;

import com.earthchen.core.base.BaseController;
import com.earthchen.core.exception.BaseException;
import com.earthchen.core.support.redis.key.shiro.ShiroKey;
import com.earthchen.core.support.redis.service.RedisService;
import com.earthchen.core.util.WebUtil;
import com.earthchen.core.vo.ResultVO;
import com.earthchen.demo.domain.SysUser;
import com.earthchen.demo.dto.SysUserDTO;
import com.earthchen.demo.dto.UserLoginDTO;
import com.earthchen.demo.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 账户controller
 */
@RestController
@RequestMapping("/account")
public class AccountController extends BaseController {


    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisService redisService;


    /**
     * 登录签发 JWT
     *
     * @return
     */
    @PostMapping("/login")
    public ResultVO accountLogin(@RequestBody UserLoginDTO userLoginDTO) {
        String jwt = sysUserService.login(userLoginDTO.getAppId(), userLoginDTO.getPassword());
        Map<String, String> map = new HashMap<>(1);
        map.put("jwt", jwt);
        return ResultVO.success(map);


    }

    /**
     * 注册
     *
     * @param sysUserDTO
     * @return
     */
    @PostMapping("/register")
    public ResultVO accountRegister(SysUserDTO sysUserDTO) {
        SysUser sysUser = sysUserService.register(sysUserDTO);
        if (sysUser == null) {
            throw new BaseException();
        }
        return ResultVO.success(sysUser);
    }


    /**
     * 用户登出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public ResultVO accountExit(HttpServletRequest request) {
        SecurityUtils.getSubject().logout();
        Map<String, String> map = WebUtil.getRequestHeaders(request);
        String appId = map.get("appId");
//        redisTemplate.opsForValue().getOperations().delete("JWT-SESSION-" + appId);
        redisService.delete(ShiroKey.getJwtSession, appId);
        return SUCCESS;
    }

}
